import logging
import models

from models import UserInPlaylist, ActiveUser, UserStat, Song, SongInPlaylist
from django.utils import simplejson as json

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.api import channel

def get_song_key(lang):
    if lang=='e':
        parent='englishsong'
    else: # lang='h'
        parent='hindisong'
    return db.Key.from_path(parent, lang)


class Test(webapp.RequestHandler):
    def get(self):
        self.response.headers['content-type']='text/plain'
        
        self.response.out.write('showing englishsong:\n')
        english_songs=Song.all().ancestor(get_song_key('e')).fetch(1000)
        for song in english_songs:
            self.response.out.write('\t'+song.songname+'\t'+str(song.timesplayed)+'\n')

            
        self.response.out.write('\nshowing hindi song:\n')
        hindi_songs=Song.all().ancestor(get_song_key('h')).fetch(1000)
        for song in hindi_songs:
            self.response.out.write('\t'+song.songname+'\t'+str(song.timesplayed)+'\n')
            
        uip=UserInPlaylist.all(keys_only=True).fetch(100)
        if len(uip)==0:
            self.response.out.write('\nno users having playlist foind :)\n')

        for u in uip:
            usr=db.get(u)
            self.response.out.write('\nshowing playlist of '+usr.user.nickname()+':\n')
            us=SongInPlaylist.all()
            us.ancestor(u)
            user_choice=us.fetch(100)
            if len(user_choice)==0:
                self.response.out.write('It turns out he is boring! ;)\n')
                continue
            cu=db.get(u)
            self.response.out.write('\tdisplaying playlist of '+cu.user.nickname()+':\n')
            for choice in user_choice:
                self.response.out.write('\t\t'+choice.song_ref.songname+'\t'+str(choice.order)+'\n')

        
        self.response.out.write('\nShowing ActiveUser:\n')
        q=ActiveUser.all()
        au=q.fetch(limit=100)
        for u in au:
            self.response.out.write(u.user.nickname()+'\n')

        self.response.out.write('\nShowing UserStat:\n')
        q=UserStat.all()
        au=q.fetch(100)
        for u in au:
            self.response.out.write('\t'+u.user.nickname()+'\t'+str(u.timesloggedin)+'\t'+str(u.lastlogin)+'\n')

def main():
    app = webapp.WSGIApplication([('/test', Test)], debug=True)
    run_wsgi_app(app)


if __name__=='__main__':
    main()
